<?php
namespace waf\client\redis;

use \waf\Waf;
use \waf\log\WLog;
class WRedisClient
{
    private $_objRedis  = null;

    function __construct($conf = array())
    {
        WLog::logInfo("in. conf=".WLog::toJson($conf), __FILE__, __LINE__, __FUNCTION__);

        if($conf)
        {
            $ip     = $conf['ip'] ?? '127.0.0.1';
            $port   = $conf['port'] ?? 6379;
            $redis = new \Swoole\Coroutine\Redis();
            $redis->connect($ip, $port);
            if($redis)
            {
                $this->_objRedis = $redis;
            }else{
                WLog::logError("redis connect error. ip=$ip, port=$port", __FILE__, __LINE__, __FUNCTION__);
            }
        }

        WLog::logInfo("out.", __FILE__, __LINE__, __FUNCTION__);
    }

    public function __call($func, $args)
    {
        $ret    = false;
        WLog::logInfo("in. func = {$func}, args=".WLog::toJson($args), __FILE__, __LINE__, __FUNCTION__);
        if($this->_objRedis)
        {
            if (method_exists($this->_objRedis, $func))
            {
                $ret = $this->_objRedis->$func(...$args);
            }
        }

        return $ret;
    }

    /**
     * 检查redis是否连接成功
     *
     * @return bool
     */
    public function isConnect()
    {
        $isRet  = false;

        if($this->_objRedis && $this->_objRedis->connected)
        {
            $isRet = true;
        }

        return $isRet;
    }

    function __destruct()
    {
        WLog::logInfo("in.", __FILE__, __LINE__, __FUNCTION__);
        unset($this->_objRedis);
        WLog::logInfo("out.", __FILE__, __LINE__, __FUNCTION__);
    }
}
?>
